package com.yymx.toback.common.exception;


import com.yymx.toback.common.base.BaseResult;
import com.yymx.toback.common.enums.CodeEnum;
import lombok.extern.slf4j.Slf4j;

import org.apache.shiro.authz.AuthorizationException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

import javax.naming.AuthenticationException;
import javax.servlet.http.HttpServletRequest;


@Slf4j
@RestController
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
    @ExceptionHandler(value =Exception.class)
    public BaseResult defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
        if(e instanceof  NullPointerException){
            log.error("Host {} invokes url {} ERROR: {}", req.getRemoteHost(), req.getRequestURL(), "NullPointerException:"+e.getMessage());
        }else if(e instanceof IllegalStateException){
            log.error("Host {} invokes url {} ERROR: {}", req.getRemoteHost(), req.getRequestURL(),  "IllegalStateException:"+e.getMessage());
        }else if(e instanceof ParamException){
            log.error("Host {} invokes url {} ERROR: {}", req.getRemoteHost(), req.getRequestURL(), e.getMessage());
            return BaseResult.failMsg("参数异常："+e.getMessage());
        }else if(e instanceof PermissionException || e instanceof AuthenticationException){
            return BaseResult.failCodeMsg(CodeEnum.TOKEN_FAIL.getCode(),e.getMessage());
        }else if(e instanceof ServiceException){
            return BaseResult.failMsg(e.getMessage());
        }
        else if(e instanceof AuthorizationException){
            return BaseResult.failCodeMsg(CodeEnum.NO_PERMISSON.getCode(),"没有操作权限");
        }
        e.printStackTrace();
        return BaseResult.failCodeAndMsg(getStatus(req).value()+"", CodeEnum.SERVICE_FAIL.getTop());
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }



}
